package pers.corvey.studyjava.service;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import pers.corvey.studyjava.dao.ChapterDAO;
import pers.corvey.studyjava.dao.CourseDAO;
import pers.corvey.studyjava.exception.BadRequestException;
import pers.corvey.studyjava.model.Chapter;
import pers.corvey.studyjava.util.FileUtils;

@Service
public class ChapterService {

    @Autowired
    private CourseDAO courseDAO;
    
    @Autowired
    private ChapterDAO chapterDAO;
    
    public Chapter getChapterById(String id) {
        return chapterDAO.findOne(id);
    }
    
    public Iterable<Chapter> getChapters(String courseId) {
        if (!courseDAO.exists(courseId)) {
            throw new BadRequestException("操作失败，该课程记录不存在！");
        }
        return chapterDAO.findByCourseId(courseId);
    }
    
    public Chapter createChapter(Chapter chapter) {
        if (!courseDAO.exists(chapter.getCourseId())) {
            throw new BadRequestException("操作失败，该课程记录不存在！");
        }
        chapter.setGmtCreate(new Date());
        chapter.setGmtModified(new Date());
        chapterDAO.save(chapter);
        return chapter;
    }
    
    public Chapter updateChapter(Chapter chapter) {
        Chapter oldChapter = chapterDAO.findOne(chapter.getId()); 
        if (oldChapter == null) {
            throw new BadRequestException("操作失败，找不到相关的章节记录！");
        }
        if (!courseDAO.exists(chapter.getCourseId())) {
            throw new BadRequestException("操作失败，该课程记录不存在！");
        }
        chapter.setGmtModified(new Date());
        chapterDAO.save(chapter);
        if (!oldChapter.getFilePath().equals(chapter.getFilePath())) {
            FileUtils.deleteFile(oldChapter.getFilePath());
        }
        return chapter;
    }
    
    public void deleteChapterById(String id) {
        chapterDAO.delete(id);
    }
    
}
